package models

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/labstack/gommon/log"
	"os"
	"time"
	// import _ "github.com/jinzhu/gorm/dialects/postgres"
	// import _ "github.com/jinzhu/gorm/dialects/sqlite"
	// import _ "github.com/jinzhu/gorm/dialects/mssql"
)

var (
	DB *gorm.DB
)

func InstanceMysql() *gorm.DB {
	if DB != nil {
		return DB
	}
	return NewMysql()
}

func NewMysql() *gorm.DB {

	connString :=os.Getenv("MYSQL_CONNECTION")
	db, err := gorm.Open("mysql", connString)

	db.LogMode(true)

	if err != nil {
		log.Fatal(err)
	}
	//设置连接池
	//空闲
	db.DB().SetMaxIdleConns(20)
	//打开
	db.DB().SetMaxOpenConns(100)
	//超时
	db.DB().SetConnMaxLifetime(time.Second * 30)

	DB =db
	return db
}
